﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

namespace HttpLogger
{
    public class SqlAuditLogger : IAuditLogger
    {
        private SqlConnectionFactory _sqlFactory;

        public SqlAuditLogger(SqlConnectionFactory sqlFactory)
        {
            _sqlFactory = sqlFactory;
        }

        public virtual void LogRecord(AuditLog record)
        {
            using(var sql = _sqlFactory.CreateConnection()) {
                    
                sql.Open();
                var cmd = sql.CreateCommand();
                cmd.CommandText = "INSERT INTO Audit(IP, url, contentType, formData, headerData, serverData, cookieData, requestData, sessionData, modulesData) " 
                                    + "VALUES(@pIP, @pUrl, @pContentType, @pFormData, @pHeaderData, @pServerData, @pCookieData, @pRequestData, @pSessionData, @pModulesData)";
                cmd.Parameters.AddWithValue("@pIP", record.IP);
                cmd.Parameters.AddWithValue("@pUrl", record.Url);
                cmd.Parameters.AddWithValue("@pContentType", (record.ResponseType == null) ? "" : record.ResponseType);
                cmd.Parameters.AddWithValue("@pFormData", (record.FormData == null) ? "" : record.FormData);
                cmd.Parameters.AddWithValue("@pHeaderData", (record.HeaderData == null) ? "" : record.HeaderData);
                cmd.Parameters.AddWithValue("@pServerData", (record.ServerData == null) ? "" : record.ServerData);
                cmd.Parameters.AddWithValue("@pCookieData", (record.CookieData == null) ? "" : record.CookieData);
                cmd.Parameters.AddWithValue("@pRequestData", (record.RequestData == null) ? "" : record.RequestData);
                cmd.Parameters.AddWithValue("@pSessionData", (record.SessionData == null) ? "" : record.SessionData );
                cmd.Parameters.AddWithValue("@pModulesData", (record.ModulesData == null) ? "" : record.ModulesData );
                cmd.ExecuteNonQuery();
            }
        }
    }
}